package com.iwe3.protal.controller;

import com.iwe3.protal.common.R;
import com.iwe3.protal.common.ShoppingGoodsInfo;
import com.iwe3.protal.service.IShoppingCarService;
import com.iwe3.protal.util.TokenUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

@Tag(name = "购物车控制器")
@RequestMapping("/shopping")
@RestController
public class ShoppingCarController {

    private final IShoppingCarService shoppingCarServiceImpl;

    public ShoppingCarController(IShoppingCarService shoppingCarServiceImpl) {
        this.shoppingCarServiceImpl = shoppingCarServiceImpl;
    }

    @Operation(summary = "查询所有购物车商品信息", parameters =
    @Parameter(name = "authentication",
            description = "token令牌",
            required = true,
            schema = @Schema(type = "string")))
    @GetMapping("/findAllGoodsInfo")
    public R findAllGoodsInfo(@RequestHeader("authentication") String token) {
        token = token.replace("Bearer ", "");
        long userId = Long.valueOf(TokenUtil.parsePayLoad(token, "sub") + "");
        // 从Redis查询出所有的 购物车商品详细
        ShoppingGoodsInfo sgi = shoppingCarServiceImpl.getMyShoppingGoodsInfo(userId);
        return R.ok(sgi);
    }

    // 完整路径：shopping/addShoppingCar
    @Operation(summary = "加入购物车", parameters = {
            @Parameter(name = "bookId",
                    description = "图书ID",
                    required = true,
                    schema = @Schema(type = "Long")),
            @Parameter(name = "token",
                    description = "token令牌",
                    required = true,
                    schema = @Schema(type = "string"))
    })
    @PostMapping("/addShoppingCar")
    public R addShoppingCar(@RequestParam("bookId") Long bookId,
                            @RequestHeader("authentication") String token) {
        token = token.replace("Bearer ", "");
        long userId = Long.valueOf(TokenUtil.parsePayLoad(token, "sub") + "");
        // 调用业务层，加入购物车
        shoppingCarServiceImpl.addShoppingCar(userId, bookId);
        return R.ok();
    }
}
